import axios from "axios";
import { isAuth } from "./token";
import { getToken } from "utils/token";
import { message } from "antd";
import { clearToken } from "./token";
// import {history} from "App";
import history from "./history";
const instance = axios.create({
  baseURL: "http://geek.itheima.net/",
  timeout: 5000,
});

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    if (isAuth()) {
      const token = "Bearer " + JSON.parse(getToken()).token;
      config.headers.Authorization = token;
    }

    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data.data;
  },
  function (error) {
    if (error?.response?.status === 401) {
      clearToken();
      // window.location.href('/login') 可以跳转，但是会刷新页面
      message.error("登录过期！");
      history.push("/login");
    }

    return Promise.reject(error);
  }
);

export default instance;
